const defaultState = {
    num: 0,
    homeData: {},
    domesticCartList: [],
    overseasCartList: [] 
}

defaultState.domesticCartList = JSON.parse(localStorage.getItem("domesticCartList")) || [];
defaultState.overseasCartList = JSON.parse(localStorage.getItem("overseasCartList")) || [];


export function reducer(state = defaultState, action) {
    let thisGoods = action.data
    switch (action.type) {
        case "HOME_DATA":
            state.homeData = action.data
            break;
        case "DOM_ADD_CART":
            // console.log(11)
            let falg = true
            state.domesticCartList.forEach((item) => {
                if (item.id === thisGoods.id && item.color === thisGoods.color && item.degree === thisGoods.degree) {
                    item.num += thisGoods.num
                    falg = false
                }
            })
            if (falg) {
                let timestamp = (new Date()).getTime();
                let math = Math.ceil(Math.random()*1000);
                let cartid = ""+timestamp+math
                state.domesticCartList.push({...thisGoods,cartId:cartid})
            }
            localStorage.setItem("domesticCartList", JSON.stringify(state.domesticCartList))
            state.num = state.domesticCartList.reduce((temp,item)=>{
                return temp+item.num
            },0)
            break;

        case "OVE_ADD_CART":
            break;

        case "DOM_MODIFY_NUM":
            state.domesticCartList.forEach((item,index) => {
                if (item.cartId === thisGoods.cartId) {
                    if(item.num>1){
                        item.num -=1
                    }else{
                        state.domesticCartList.splice(index,1)

                    }
                }
            })
            
            break;

        case "OVE_MODIFY_NUM":
            break;

        case "DOM_IS_SELECT":
            state.domesticCartList.forEach((item) => {
                if (item.cartId === thisGoods.cartId) {
                   item.isSelect = !item.isSelect
                }
            })
            break;

        case "OVE_IS_SELECT":
            break;

        case "DOM_ALL_SELECT":
            state.domesticCartList.forEach((item) => {
                item.isSelect = !thisGoods.cartId
            })
            break;
            
        case "OVE_ALL_SELECT":
            break;
        default:
            break;
    }
    localStorage.setItem("domesticCartList",JSON.stringify(state.domesticCartList))
    return JSON.parse(JSON.stringify(state));
}